package com.knife.scheduler.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.knife.scheduler.app.service.KnifeJobInfoService;
import com.knife.scheduler.domain.entity.KnifeJobInfo;
import com.knife.scheduler.domain.service.KnifeJobService;
import com.knife.scheduler.infra.mapper.KnifeJobInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： 76875
 * @date： 2022/4/2 星期六 23:09
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Service
public class KnifeJobInfoServiceImpl implements KnifeJobInfoService {

    @Autowired
    private KnifeJobInfoMapper knifeJobInfoMapper;

    @Autowired
    private KnifeJobService knifeJobService;

    @Override
    public Page<KnifeJobInfo> selectKnifeJobInfoPage(KnifeJobInfo knifeJobInfo, Page<KnifeJobInfo> page) {
        QueryWrapper<KnifeJobInfo> knifeJobInfoQueryWrapper = new QueryWrapper<>();
        knifeJobInfoQueryWrapper.like(!ObjectUtils.isEmpty(knifeJobInfo.getJobCode()), "job_code", knifeJobInfo.getJobCode())
                .like(!ObjectUtils.isEmpty(knifeJobInfo.getQuartzName()), "quartz_name", knifeJobInfo.getQuartzName())
                .like(!ObjectUtils.isEmpty(knifeJobInfo.getDescription()), "description", knifeJobInfo.getDescription())
                .like(!ObjectUtils.isEmpty(knifeJobInfo.getQuartzGroup()), "quartz_group", knifeJobInfo.getQuartzGroup());
        return knifeJobInfoMapper.selectPage(page, knifeJobInfoQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAndUpdateKnifeJobInfo(KnifeJobInfo knifeJobInfo) {
        if (ObjectUtils.isEmpty(knifeJobInfo.getId())){
            knifeJobInfoMapper.insert(knifeJobInfo);
            KnifeJobInfo jobInfo = knifeJobInfoMapper.selectById(knifeJobInfo.getId());
            knifeJobService.createJob(jobInfo);
        }else {
            knifeJobInfoMapper.updateById(knifeJobInfo);
            // 更新任务
            knifeJobService.updateJob(knifeJobInfo);
        }
    }
}
